"""
配置管理模块
"""

import os
import logging.config
from dataclasses import dataclass
from typing import Dict, Tuple
from pathlib import Path

@dataclass
class WeiboConfig:
    """微博爬虫配置类"""
    base_url: str = "https://m.weibo.cn/api/container/getIndex"
    timeout: int = 15
    max_retries: int = 3
    retry_delay: float = 5.0
    request_delay: Tuple[float, float] = (2, 5)
    max_pages: int = 10
    page_size: int = 10
    
    # 请求头配置
    headers: Dict = None
    
    def __post_init__(self):
        if self.headers is None:
            self.headers = {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36',
                'x-requested-with': 'XMLHttpRequest',
            }

# 将 get_config 方法移到类外部，作为模块级别的函数
def get_weibo_config(env: str = None) -> WeiboConfig:
    """获取微博配置"""
    env = env or os.getenv('ENVIRONMENT', 'development')
    
    if env == 'production':
        return WeiboConfig(
            max_pages=5,
            request_delay=(3, 7),
            max_retries=5
        )
    else:  # development
        return WeiboConfig(
            max_pages=3,
            request_delay=(2, 5),
            max_retries=3
        )

def get_logging_config():
    """获取日志配置"""
    
    # 确保日志目录存在
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    logging_config = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
            },
            'detailed': {
                'format': '%(asctime)s [%(levelname)s] %(name)s:%(lineno)d: %(message)s'
            },
        },
        'handlers': {
            'default': {
                'level': 'INFO',
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
                'stream': 'ext://sys.stdout',
            },
            'file': {
                'level': 'DEBUG',
                'formatter': 'detailed',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': 'logs/weibo_crawler.log',
                'maxBytes': 10485760,  # 10MB
                'backupCount': 5,
                'encoding': 'utf-8'
            },
            'error_file': {
                'level': 'ERROR',
                'formatter': 'detailed',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': 'logs/error.log',
                'maxBytes': 10485760,  # 10MB
                'backupCount': 5,
                'encoding': 'utf-8'
            }
        },
        'loggers': {
            '': {  # root logger
                'handlers': ['default', 'file', 'error_file'],
                'level': 'DEBUG',
                'propagate': False
            },
            'app': {
                'handlers': ['default', 'file', 'error_file'],
                'level': 'DEBUG',
                'propagate': False
            },
            'core': {
                'handlers': ['default', 'file', 'error_file'],
                'level': 'DEBUG',
                'propagate': False
            },
            'models': {
                'handlers': ['default', 'file', 'error_file'],
                'level': 'DEBUG',
                'propagate': False
            }
        }
    }
    
    return logging_config

def setup_logging():
    """设置日志配置"""
    config = get_logging_config()
    logging.config.dictConfig(config)